from sqlalchemy.orm import mapped_column, Mapped
from fastapi_users.db import SQLAlchemyBaseUserTable
from extensions.db.model import Base
import sqlalchemy
from sqlalchemy.orm import relationship
import datetime
from typing import List

"""
rbac权限模型
"""

# 用户-角色-中间表
class UserRole(Base):
    __tablename__ = "user_role"
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    user_id = sqlalchemy.Column(
        sqlalchemy.ForeignKey("user.id"), comment="用户id")
    role_id = sqlalchemy.Column(
        sqlalchemy.ForeignKey("role.id"), comment="角色id")
    create_data = sqlalchemy.Column(
        server_default=sqlalchemy.func.now())

# 用户模型
class User(SQLAlchemyBaseUserTable[int], Base):
    """
    secondary = UserRole.__table__指定中间表方便对中间表进行操作,如不需要则写UserRole即可
    """
    id: Mapped[int] = mapped_column(sqlalchemy.Integer, primary_key=True)
    username: Mapped[str] = mapped_column(sqlalchemy.String(255), comment="姓名")
    roles: Mapped[List["Role"]] = relationship(
        secondary=UserRole.__table__, back_populates="users")

class RolePower(Base):
    __tablename__ = "role_power"
    id = sqlalchemy.Column(primary_key=True)
    role_id = sqlalchemy.Column(
        sqlalchemy.ForeignKey("role.id"), comment="角色id")
    power_id = sqlalchemy.Column(
        sqlalchemy.ForeignKey("power.id"), comment="权限id")


class Role(Base):
    __tablename__ = "role"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(sqlalchemy.String(255), comment="名字")
    create_data: Mapped[datetime.datetime] = mapped_column(
        server_default=sqlalchemy.func.now())
    users: Mapped[List[User]] = relationship(
        secondary=UserRole.__table__, back_populates="roles")
    powers: Mapped[List["Power"]] = relationship(
        secondary=RolePower.__table__, back_populates="roles")


class Power(Base):
    __tablename__ = "power"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(sqlalchemy.String(255), comment="名字")
    create_data: Mapped[datetime.datetime] = mapped_column(
        server_default=sqlalchemy.func.now())
    roles: Mapped[List[Role]] = relationship(
        secondary=RolePower.__table__, back_populates="powers")
